from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field
from typing import Dict, Optional, List, Any
import json

class Settings(BaseSettings):
    """应用配置类"""
    
    # Dify API配置
    dify_base_url: str = Field(..., env="DIFY_BASE_URL")
    dify_api_key: str = Field(..., env="DIFY_API_KEY")
    
    # 日志配置
    log_level: str = Field("INFO", env="LOG_LEVEL")
    
    # 工作流集成配置
    workflow_enabled: bool = Field(False, env="WORKFLOW_ENABLED")
    workflow_base_url: Optional[str] = Field(None, env="WORKFLOW_BASE_URL")
    workflow_api_endpoint: str = Field("/api/workflow/kb-update", env="WORKFLOW_API_ENDPOINT")
    workflow_timeout: int = Field(30, env="WORKFLOW_TIMEOUT")
    
    # 安全配置
    api_key_required: bool = Field(True, env="API_KEY_REQUIRED")
    api_key: Optional[str] = Field(None, env="API_KEY")
    rate_limit_enabled: bool = Field(True, env="RATE_LIMIT_ENABLED")
    rate_limit_per_minute: int = Field(60, env="RATE_LIMIT_PER_MINUTE")
    rate_limit_per_hour: int = Field(1000, env="RATE_LIMIT_PER_HOUR")
    
    # 访问控制配置
    allowed_origins: str = Field("*", env="ALLOWED_ORIGINS")
    log_external_access: bool = Field(True, env="LOG_EXTERNAL_ACCESS")
    
    # 知识库工作流映射配置（10个知识库）
    kb_01_id: Optional[str] = Field(None, env="KB_01_ID")
    kb_01_workflow_key: Optional[str] = Field(None, env="KB_01_WORKFLOW_KEY")
    
    kb_02_id: Optional[str] = Field(None, env="KB_02_ID")
    kb_02_workflow_key: Optional[str] = Field(None, env="KB_02_WORKFLOW_KEY")
    
    kb_03_id: Optional[str] = Field(None, env="KB_03_ID")
    kb_03_workflow_key: Optional[str] = Field(None, env="KB_03_WORKFLOW_KEY")
    
    kb_04_id: Optional[str] = Field(None, env="KB_04_ID")
    kb_04_workflow_key: Optional[str] = Field(None, env="KB_04_WORKFLOW_KEY")
    
    kb_05_id: Optional[str] = Field(None, env="KB_05_ID")
    kb_05_workflow_key: Optional[str] = Field(None, env="KB_05_WORKFLOW_KEY")
    
    kb_06_id: Optional[str] = Field(None, env="KB_06_ID")
    kb_06_workflow_key: Optional[str] = Field(None, env="KB_06_WORKFLOW_KEY")
    
    kb_07_id: Optional[str] = Field(None, env="KB_07_ID")
    kb_07_workflow_key: Optional[str] = Field(None, env="KB_07_WORKFLOW_KEY")
    
    kb_08_id: Optional[str] = Field(None, env="KB_08_ID")
    kb_08_workflow_key: Optional[str] = Field(None, env="KB_08_WORKFLOW_KEY")
    
    kb_09_id: Optional[str] = Field(None, env="KB_09_ID")
    kb_09_workflow_key: Optional[str] = Field(None, env="KB_09_WORKFLOW_KEY")
    
    kb_10_id: Optional[str] = Field(None, env="KB_10_ID")
    kb_10_workflow_key: Optional[str] = Field(None, env="KB_10_WORKFLOW_KEY")
    
    model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
    
    def get_knowledge_base_config(self, dataset_id: str) -> Optional[Dict[str, Any]]:
        """根据知识库ID获取配置（包含工作流key）"""
        # 构建知识库映射表
        kb_mappings = {
            self.kb_01_id: {"workflow_key": self.kb_01_workflow_key, "kb_id": "01"},
            self.kb_02_id: {"workflow_key": self.kb_02_workflow_key, "kb_id": "02"},
            self.kb_03_id: {"workflow_key": self.kb_03_workflow_key, "kb_id": "03"},
            self.kb_04_id: {"workflow_key": self.kb_04_workflow_key, "kb_id": "04"},
            self.kb_05_id: {"workflow_key": self.kb_05_workflow_key, "kb_id": "05"},
            self.kb_06_id: {"workflow_key": self.kb_06_workflow_key, "kb_id": "06"},
            self.kb_07_id: {"workflow_key": self.kb_07_workflow_key, "kb_id": "07"},
            self.kb_08_id: {"workflow_key": self.kb_08_workflow_key, "kb_id": "08"},
            self.kb_09_id: {"workflow_key": self.kb_09_workflow_key, "kb_id": "09"},
            self.kb_10_id: {"workflow_key": self.kb_10_workflow_key, "kb_id": "10"},
        }
        
        # 查找匹配的知识库配置
        for kb_id, config in kb_mappings.items():
            if kb_id and kb_id == dataset_id:
                return {
                    "dataset_id": kb_id,
                    "workflow_key": config["workflow_key"],
                    "kb_number": config["kb_id"]
                }
        
        return None
    
    def get_all_managed_knowledge_bases(self) -> List[str]:
        """获取所有受管理的知识库ID列表"""
        kb_ids = [
            self.kb_01_id, self.kb_02_id, self.kb_03_id, self.kb_04_id, self.kb_05_id,
            self.kb_06_id, self.kb_07_id, self.kb_08_id, self.kb_09_id, self.kb_10_id
        ]
        return [kb_id for kb_id in kb_ids if kb_id]
    
    def get_workflow_config_by_key(self, workflow_key: str) -> Optional[Dict[str, Any]]:
        """根据工作流key获取配置"""
        # 构建工作流密钥映射表
        workflow_mappings = {
            self.kb_01_workflow_key: {"kb_id": self.kb_01_id, "kb_number": "01"},
            self.kb_02_workflow_key: {"kb_id": self.kb_02_id, "kb_number": "02"},
            self.kb_03_workflow_key: {"kb_id": self.kb_03_id, "kb_number": "03"},
            self.kb_04_workflow_key: {"kb_id": self.kb_04_id, "kb_number": "04"},
            self.kb_05_workflow_key: {"kb_id": self.kb_05_id, "kb_number": "05"},
            self.kb_06_workflow_key: {"kb_id": self.kb_06_id, "kb_number": "06"},
            self.kb_07_workflow_key: {"kb_id": self.kb_07_id, "kb_number": "07"},
            self.kb_08_workflow_key: {"kb_id": self.kb_08_id, "kb_number": "08"},
            self.kb_09_workflow_key: {"kb_id": self.kb_09_id, "kb_number": "09"},
            self.kb_10_workflow_key: {"kb_id": self.kb_10_id, "kb_number": "10"},
        }
        
        # 查找匹配的工作流配置
        for wf_key, config in workflow_mappings.items():
            if wf_key and wf_key == workflow_key:
                return {
                    "workflow_key": workflow_key,
                    "dataset_id": config["kb_id"],
                    "kb_number": config["kb_number"]
                }
        
        return None

# 创建配置实例
settings = Settings()


# 加载简单 ID 到 UUID 的映射 from kb-api_key.txt
def load_id_mappings() -> Dict[str, str]:
    mappings = {}
    try:
        with open('kb-api_key.txt', 'r') as f:
            for line in f:
                parts = line.strip().split()
                if len(parts) >= 2:
                    simple_id = parts[0].lstrip('0')  # 去掉前导0，如 01 -> 1
                    uuid = parts[1]
                    mappings[simple_id] = uuid
    except FileNotFoundError:
        pass  # 如果文件不存在，返回空映射
    return mappings

# 根据输入数字获取对应的app key
def get_app_key_by_number(number: str) -> Optional[str]:
    try:
        with open('kb-api_key.txt', 'r') as f:
            for line in f:
                parts = line.strip().split()
                if len(parts) >= 3 and parts[0].lstrip('0') == number:
                    return parts[2]  # 返回app key
    except FileNotFoundError:
        pass  # 如果文件不存在，返回None
    return None

simple_id_to_uuid = load_id_mappings()